package com.app.web.stomp
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.env.Environment
import org.springframework.messaging.Message
import org.springframework.messaging.MessageChannel
import org.springframework.messaging.simp.SimpMessageHeaderAccessor
import org.springframework.messaging.simp.config.ChannelRegistration
import org.springframework.messaging.simp.config.MessageBrokerRegistry
import org.springframework.messaging.support.ChannelInterceptor
import org.springframework.messaging.support.ChannelInterceptorAdapter
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker
import org.springframework.web.socket.config.annotation.StompEndpointRegistry
import org.springframework.web.socket.server.HandshakeHandler
/**
 * Created by three on 14-10-8.
 */
@CompileStatic
@TypeChecked
@Configuration
@EnableWebSocketMessageBroker
class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    private static final String SESSION_ATTR = "httpSession.id";
    private static final String SOCKJS_CLIENT_URL = "http://127.0.0.1:9000/bower_components/sockjs-client/dist/sockjs.js";
    @Autowired
    Environment env;

//    @Autowired
//    SessionRepository sessionRepository;

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //添加这个Endpoint，这样在网页中就可以通过websocket连接上服务了
        registry.addEndpoint("/connect")
                .addInterceptors(new MyHandshakeInterceptor())
                .setHandshakeHandler(handshakeHandler())
                .withSockJS()
                .setWebSocketEnabled(true)
                .setClientLibraryUrl(SOCKJS_CLIENT_URL);
    }
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        //这里设置的simple broker是指可以订阅的地址，也就是服务器可以发送的地址

        config.enableSimpleBroker("/topic","/echo","/queue","/init");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        // 设置接收客户端消息拦截器
        registration.setInterceptors(sessionContextChannelInterceptorAdapter());
    }

    @Bean
    HandshakeHandler handshakeHandler() {
        return new MyHandshakeHandler();
    }

    @Bean
    ChannelInterceptor sessionContextChannelInterceptorAdapter() {
        return new ChannelInterceptorAdapter() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                Map<String, Object> sessionHeaders = SimpMessageHeaderAccessor.getSessionAttributes(message.getHeaders());
                String sessionId = (String) sessionHeaders.get(SESSION_ATTR);
                /*if (sessionId != null) {
                    Session session = sessionRepository.getSession(sessionId);
                    if (session != null) {

                        sessionRepository.save(session);
                    }
                }*/
                return super.preSend(message, channel);
            }
        };
    }
}
